import React from 'react';
import './style.css';
// event
import emitter from '../../util/events';
// antd
import { Form, Row, Col, Select, Card, Button, Checkbox, Table, Input } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;

class AttrInfoForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // 表头
            columns: [
                {
                    title: 'POA',
                    dataIndex: 'POA',
                    key: 'POA'
                },
                {
                    title: '属性',
                    dataIndex: 'Attribute',
                    key: 'Attribute'
                },
                {
                    title: '售价',
                    dataIndex: 'Price',
                    key: 'Price'
                },
                {
                    title: '数量',
                    dataIndex: 'Amount',
                    key: 'Amount'
                }
            ],
            // 多属性选择(已选择)
            attrSelect: [], 
            // 表格数据
            tableData: [],
            // 多属性选择数据
            selectData: [
                {
                    value: 'Size',
                    label: 'Size',
                    data: ['S', 'M', 'L', 'XL', 'XXL', 'XXXL']
                }, {
                    value: 'Color',
                    label: 'Color',
                    data: ['Blue', 'Green', 'Red', 'Yellow', 'White', 'Block']
                }, {
                    value: 'CN',
                    label: 'CN',
                    data: ['Blue1', 'Green1', 'Red1', 'Yellow1', 'White1', 'Block1']
                }, {
                    value: 'Germany',
                    label: 'Germany'
                }, {
                    value: 'France',
                    label: 'France'
                }, {
                    value: 'United Kingdom',
                    label: 'United Kingdom'
                }, {
                    value: 'Gibraltar',
                    label: 'Gibraltar'
                }, {
                    value: 'Hong Kong',
                    label: 'Hong Kong'
                }, {
                    value: 'lreland',
                    label: 'lreland'
                }, {
                    value: 'Morocco',
                    label: 'Morocco'
                }, {
                    value: 'Netherlands',
                    label: 'Netherlands'
                }, {
                    value: 'Singapore',
                    label: 'Singapore'
                }, {
                    value: 'USA',
                    label: 'USA'
                }, {
                    value: 'Malaysla',
                    label: 'Malaysla'
                },
            ]
        };
        
        this.attrSelect = [];
        // this.attrCheckData = {};
    }
    // 多属性选择共用方法
    columns = (type, value, attrSelect) => {
        this.setState({
            attrSelect
        })
        this.sendData(attrSelect);
        // 表格动态展示
        let columns = this.state.columns;
        let obj = {};
        if (type === 'onSelect') {
            obj["title"] = obj["dataIndex"] = obj["key"] = value;
            for (let i = 0; i < columns.length; i++) {
                if (columns[i]["title"] === '售价') {
                    columns.splice(i, 0, obj);
                    break;
                }
            }
        } else if (type === 'onDeselect') {
            columns = columns.filter(d => d["title"] !== value)
        }
        this.setState({
            columns
        })
    }
    // 多属性选择select事件
    onSelect = (value, option) => {
        // 添加多属性选择
        let attrSelect = this.state.attrSelect;
        let obj = {};
        obj["label"] = value;
        obj["data"] = []
        attrSelect.push(obj);
        this.columns('onSelect', value, attrSelect)
    }
    // 多属性选择deselect事件
    onDeselect = (value, option) => {
        // 删除多属性选择
        let attrSelect = this.state.attrSelect;
        attrSelect = attrSelect.filter(d => d.label !== value);
        this.columns('onDeselect', value, attrSelect);
        // let tableData = []
        // delete this.attrCheckData[value]
        // if(Object.keys(this.attrCheckData).length !== 0) {
        //     let arr = [];
        //     let keys = [];
        //     for(let key in this.attrCheckData){
        //         keys.push(key);
        //         arr.push(this.attrCheckData[key]);
        //     };
        //     let total = this.doExchange(arr);
        //     tableData = total.map(d => {
        //         let obj = {};
        //         d.split("|").map((el, index) => {
        //             obj[keys[index]] = el;
        //         })
        //         return obj
        //     });
        // } else {
        //     tableData = []
        // }
        // this.setState({
        //     tableData
        // });
    }
    // EAN UPC MPN 点击事件
    attrInfoChange = (checkedValue) => {
        let columns = this.state.columns;
        let index = null;
        for (let i = 0; i < columns.length; i++) {
            if (columns[i]["title"] === '数量') {
                index = i;
                break;
            }
        }
        columns.splice(index + 1)
        checkedValue.map(d => {
            let obj = {};
            obj["title"] = obj["dataIndex"] = obj["key"] = d;
            columns.push(obj)
            return true;
        })
        this.setState({
            columns
        })
    }
    // attrCheck多属性点击事件
    attrCheck = (checkedValue, type) => {
        let attrSelect = this.state.attrSelect;
        attrSelect = attrSelect.map((el, index) => {
            if(el === type) {
                let dataItems = []
                for(let i = 0; i < checkedValue.length; i++) {
                    let dataItem = {};
                    dataItem["label"] = checkedValue[i];
                    dataItem["fileList"] = [];
                    dataItems.push(dataItem);
                }
                el.data = dataItems;
            }
            return el;
        })
        this.setState({
            attrSelect
        })

        let arrs = [];
        let keys = [];
        attrSelect.map((el, index) => {
            let arr = el.data.map(d => d.label);
            if(el.data.length > 0) {
                arrs.push(arr);
                keys.push(el.label);
            };
            return true;
        })
        let tableData = [];
        if(arrs.length > 0) {
            let total = this.doExchange(arrs);
            tableData = total.map(d => {
                let obj = {};
                d.split("|").map((el, index) => {
                    obj[keys[index]] = el;
                    return true;
                })
                return obj
            });
        } else {
            tableData = []
        }
        
        this.setState({
            tableData
        });
        this.sendData(attrSelect)
    }
    // 添加属性值
    addAttrCheck = (e, type) => {
        let selectData = this.state.selectData.filter(d => {
            if(d.value === type && this.refs[type].input.value.trim !== '' && this.refs[type].input.value) {
                d.data.push(this.refs[type].input.value)
            }
            return d;
        })
        this.setState({
            selectData
        });
        this.refs[type].input.value = '';
    }
    // 多数组组合排列
    doExchange(arr) {
        var len = arr.length;
        // 当数组大于等于2个的时候
        if (len >= 2) {
            // 第一个数组的长度
            var len1 = arr[0].length;
            // 第二个数组的长度
            var len2 = arr[1].length;
            // 2个数组产生的组合数
            var lenBoth = len1 * len2;
            //  申明一个新数组,做数据暂存
            var items = new Array(lenBoth);
            // 申明新数组的索引
            var index = 0;
            // 2层嵌套循环,将组合放到新数组中
            for (let i = 0; i < len1; i++) {
                for (var j = 0; j < len2; j++) {
                    items[index] = arr[0][i] + "|" + arr[1][j];
                    index++;
                }
            }
            // 将新组合的数组并到原数组中
            var newArr = new Array(len - 1);
            for (let ind = 2; ind < arr.length; ind++) {
                newArr[ind - 1] = arr[ind];
            }
            newArr[0] = items;
            // 执行回调
            return this.doExchange(newArr);
        } else {
            return arr[0];
        }
    }
    // // 传递数据
    sendData = (data) => {
        emitter.emit('sendData', data)
    }
    render() {
        const formItemLayout = {
            labelCol: {
                sm: { span: 5 },
            },
            wrapperCol: {
                sm: { span: 18 },
            },
        };

        const { getFieldDecorator } = this.props.form;

        // 多属性选择select
        const Options = this.state.selectData.map((el, index) => {
            return <Option key={el.value} value={el.value}>{el.label}</Option>
        })
        // cards 多属性选择(已选中的值遍历card)
        const cards = this.state.attrSelect.map((d, index) => {
            let CheckboxGroups;
            for (let i = 0; i < this.state.selectData.length; i++) {
                if (this.state.selectData[i]['value'] === d.label) {
                    this.state.selectData[i]['data'] && (CheckboxGroups = <CheckboxGroup data-type={d.label} options={this.state.selectData[i]['data']} onChange={(checkedValue) => {this.attrCheck(checkedValue, d)}}></CheckboxGroup>)
                    break;
                }
            }
            return (
                <Card key={index} title={d.label}>
                    <div className="AttributeContent">
                        {
                            CheckboxGroups
                        }
                    </div>
                    <FormItem label="自定义尺寸"
                        {
                        ...{
                            labelCol: {
                                sm: { span: 2 },
                            },
                            wrapperCol: {
                                sm: { span: 22 },
                            },
                        }
                        } style={{ margin: 0 }}>
                        <Row gutter={8}>
                            <Col span={8}>
                                <Input ref={d.label}/>
                            </Col>
                            <Col>
                                <Button type="primary" onClick={(e) => {this.addAttrCheck(e, d.label)}}>添加</Button>
                            </Col>
                        </Row>
                    </FormItem>
                </Card>
            )
        })
        // EAN UPC MPN
        const attrInfoChecke = [
            { label: '自定义EAN', value: 'EAN' },
            { label: '自定义UPC', value: 'UPC' },
            { label: '自定义MPN', value: 'MPN' },
        ];

        return (
            <div className="AttrInfoForm">
                <FormItem label="多属性选择" {...formItemLayout}>
                    <Row gutter={8}>
                        <Col span={8}>
                            {
                                getFieldDecorator('AttrSelect')(
                                    <Select
                                        mode="tags"
                                        onSelect={this.onSelect}
                                        onDeselect={this.onDeselect}
                                        placeholder="请选择"
                                        style={{ width: '100%' }}
                                    >
                                        {Options}
                                    </Select>
                                )
                            }
                        </Col>
                    </Row>
                </FormItem>

                {
                    cards
                }

                <Card title="POA">
                    <FormItem label="一键填充" {
                        ...{
                            labelCol: {
                                sm: { span: 2 },
                            },
                            wrapperCol: {
                                sm: { span: 22 },
                            },
                        }
                    }>
                        <Row gutter={8}>
                            <Col span={4}>
                                {
                                    getFieldDecorator('POA')(
                                        <Input placeholder="请输入SKU/POA/产品组" />
                                    )
                                }
                            </Col>
                            <Col span={20} className="POAAttrInfo">
                                <Button type="primary">一键</Button>
                                <Button type="primary">选择添加</Button>

                                <CheckboxGroup options={attrInfoChecke} onChange={this.attrInfoChange} />
                            </Col>
                        </Row>
                    </FormItem>

                    <Table
                        pagination={false}
                        bordered={true}
                        columns={this.state.columns}
                        dataSource={this.state.tableData} />
                </Card>
            </div>
        );
    }
}

export default Form.create()(AttrInfoForm)